all repos — caroster @ 7c2a4deb29ac359bf7caf40481f451f3024462a6

[Octree] Group carpool to your event https://caroster.io

frontend/pages/api/nauth/[...nextauth].js (view raw)

 1import NextAuth from 'next-auth';
 2import CredentialsProvider from 'next-auth/providers/credentials';
 3import GoogleProvider from 'next-auth/providers/google';
 4
 5const {STRAPI_URL = 'http://localhost:1337'} = process.env;
 6
 7const authHandler = NextAuth({
 8  providers: [
 9    CredentialsProvider({
10      name: 'Strapi',
11      credentials: {
12        email: {label: 'Email', type: 'text'},
13        password: {label: 'Password', type: 'password'},
14      },
15      async authorize(credentials, req) {
16        const response = await fetch(`${STRAPI_URL}/api/auth/local`, {
17          method: 'POST',
18          headers: {'Content-Type': 'application/json'},
19          body: JSON.stringify({
20            identifier: credentials.email,
21            password: credentials.password,
22          }),
23        });
24        const data = await response.json();
25        if (data?.error?.message === 'Your account email is not confirmed')
26          throw new Error('EmailNotConfirmed');
27        else if (!data?.jwt) return null;
28        else {
29          const {user, jwt} = data;
30          return {...user, jwt};
31        }
32      },
33    }),
34    GoogleProvider({
35      clientId: process.env.GOOGLE_CLIENT_ID,
36      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
37    }),
38  ],
39  session: {
40    jwt: true,
41  },
42  callbacks: {
43    jwt: async params => {
44      const {token, user, account} = params;
45
46      // Google Auth
47      if (account?.provider === 'google') {
48        try {
49          const strapiUrl = process.env.STRAPI_URL || 'http://localhost:1337';
50          const response = await fetch(
51            `${strapiUrl}/api/auth/${account.provider}/callback?access_token=${account?.access_token}`
52          );
53          const data = await response.json();
54          token.id = data.user.id;
55          token.jwt = data.jwt;
56          token.email = data.user.email;
57          token.username = data.user.firstname;
58          token.lang = data.user.lang?.toLowerCase();
59          token.provider = account.provider;
60          token.userCreatedAt = data.user.createdAt;
61        } catch (error) {
62          console.error("Can't authenticate with Google to Strapi: ", error);
63        }
64      }
65
66      // Strapi Auth
67      else if (user) {
68        token.id = user.id;
69        token.jwt = user.jwt;
70        token.email = user.email;
71        token.username = user.firstname;
72        token.lang = user.lang?.toLowerCase();
73        token.provider = account.provider;
74        token.userCreatedAt = user.createdAt;
75      }
76
77      return token;
78    },
79    session: async params => {
80      const {session, token} = params;
81      if (session) {
82        session.token = token;
83        session.user.name = token.username;
84        session.user.lang = token.lang;
85      }
86      return session;
87    },
88  },
89  pages: {
90    signIn: '/auth/login',
91    error: '/auth/login',
92  },
93});
94
95export default async function handler(...params) {
96  await authHandler(...params);
97}